/*
 * <<
 *  Davinci
 *  ==
 *  Copyright (C) 2016 - 2019 EDP
 *  ==
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  >>
 *
 */

package com.cwf.quality.handler;

import com.cwf.quality.common.enums.HttpCodeEnum;
import com.cwf.quality.common.exception.ForbiddenException;
import com.cwf.quality.common.exception.NotFoundException;
import com.cwf.quality.common.exception.ServerException;
import com.cwf.quality.model.vo.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice(annotations = RestController.class)
@Slf4j
public class RestExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private ResultResponse commonExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return new ResultResponse().fail(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
    }

    @ExceptionHandler(value = ServerException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private ResultResponse serverExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return new ResultResponse().fail(e.getMessage());
    }

    @ExceptionHandler(value = ForbiddenException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.FORBIDDEN)
    private ResultResponse forbiddenExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return new ResultResponse().fail(HttpCodeEnum.FORBIDDEN.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = NotFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private ResultResponse notFoundExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return new ResultResponse().fail(HttpCodeEnum.NOT_FOUND.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private ResultResponse methodArgumentNotValidExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return new ResultResponse().fail(HttpCodeEnum.FAIL.getCode(), e.getMessage());
    }

}
